package cn.itrip.auth.service;

import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import com.alibaba.fastjson.JSON;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
* @Description: ToKen认证
* @Author: XiaoKun
* @Date: 2019-01-26
*/
@Service("tokenService")
public class TokenServiceImpl implements TokenService {
    private long protectedTime = 30 * 60 * 1000;
    private int delay = 2 * 60;
    @Resource
    private RedisAPI redisAPI;

    /**
     * 生成token
     *
     * @param userAgent
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String geterateToken(String userAgent, ItripUser user) throws Exception {
        StringBuilder str = new StringBuilder();
        str.append("token:");
        UserAgent agent = UserAgent.parseUserAgentString(userAgent);
        //判断终端
        if (agent.getOperatingSystem().isMobileDevice()) {
            str.append("MOBILE-");
        } else {
            str.append("PC-");
        }
        str.append(MD5.getMd5(user.getUserCode(), 32) + "-");
        str.append(user.getId().toString() + "-");
        str.append(new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date()) + "-");
        str.append(MD5.getMd5(userAgent, 6));
        return str.toString();
    }

    /**
     * 延迟ToKen有效期
     * @param token
     * @param user
     * @throws Exception
     */
    @Override
    public void save(String token, ItripUser user) throws Exception {
        if (token.startsWith("token:PC-")) {
            redisAPI.set(token, 2 * 60 * 60, JSON.toJSONString(user));
        } else {
            redisAPI.set(token, JSON.toJSONString(user));
        }
    }

    /**
     * token校验
     *
     * @param userAgent
     * @param token
     * @return
     * @throws Exception
     */
    @Override
    public boolean validate(String userAgent, String token) throws Exception {
        if (!redisAPI.exist(token)) {
            return false;
        }
        String agentMD5 = token.split("-")[4];
        if (!MD5.getMd5(userAgent, 6).equals(agentMD5)) {
            return false;
        }
        return true;
    }

    /**
     * 删除token
     *
     * @param token
     */
    @Override
    public void delToken(String token) {
        redisAPI.delete(token);
    }


    /**
     * 置换token
     *
     * @param userAgent
     * @param token
     */
    @Override
    public String reloadToken(String userAgent, String token) throws Exception {
        //验证token是否有效
        if (!redisAPI.exist(token)) {
            throw new Exception("token无效");
        }
        //能不能够被置换
        Date genTime = new SimpleDateFormat("yyyyMMddHHmmsss").parse(token.split("-")[3]);
        long passed = Calendar.getInstance().getTimeInMillis() - genTime.getTime();
        if (passed < protectedTime) {
            throw new Exception("token置换保护期内，不能置换，剩余:" + (protectedTime - passed) / 1000);
        }
        //进行置换
        String user = redisAPI.get(token);
        ItripUser itripUser = JSON.parseObject(user, ItripUser.class);
        String newToken = this.geterateToken(userAgent, itripUser);
        //旧延时过期
        redisAPI.set(token, delay, user);
        //新的tonken置换到redis
        this.save(newToken, itripUser);
        return newToken;
    }
}
